package cn.lyjuan.archetypes.bms.web.taglib;

import javax.servlet.jsp.JspException;
import java.io.IOException;

/**
 * 处理配置的地址后缀，Spring 仅拦截该后缀的请求
 */
public class BmsSuffixTag extends BaseTag
{
    private String url;

    /**
     * URL拼接后缀
     *
     * @param url
     * @return
     */
    public static String suffix(String url)
    {
        if (null == url || "".equals(url.trim()))
            return "";

        if (url.indexOf(".") > -1)
            return url;

        if (url.endsWith("/"))// 目录
            return url;

        // 带参数
        int hasParam = url.indexOf("?");
        if (hasParam > -1)
            return url.substring(0, hasParam) + getSuffix() + url.substring(hasParam);

        return url + getSuffix();
    }

    /**
     * 直接获取后缀，带"."
     *
     * @return
     */
    public static String getSuffix()
    {
        return sysProperties().getUrlSuffix();
    }

    @Override
    public int doStartTag() throws JspException
    {
        // 拼接后缀
        String suffixUrl = suffix(this.url);

        try
        {
            this.pageContext.getOut().print(suffixUrl);
        } catch (IOException e)
        {
            throw new JspException("Print BmsSuffixTag Error", e);
        }

        return EVAL_PAGE;
    }

    @Override
    public int doEndTag() throws JspException
    {
        return EVAL_PAGE;
    }

    public String getUrl()
    {
        return url;
    }

    public void setUrl(String url)
    {
        this.url = url;
    }
}
